<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useAuthStore } from '../../store/useAuthStore'
import type { LoginRequest } from '../../types/auth'
import { ElMessage } from 'element-plus'
import { User, Lock, Link } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()

// 表单数据
const loginForm = reactive<LoginRequest>({
  username: '',
  password: '',
  remember: true
})

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度应为3-20个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 30, message: '密码长度应为6-30个字符', trigger: 'blur' }
  ]
}

// 表单引用
const formRef = ref()

// 提交状态
const isSubmitting = ref(false)

// 提交登录表单
const handleSubmit = async () => {
  // 表单验证
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    isSubmitting.value = true
    
    console.log('开始登录流程...')
    // 调用登录方法
    const success = await authStore.login(loginForm)
    
    if (success) {
      console.log('登录成功，准备跳转...')
      console.log('当前认证状态:', authStore.isAuthenticated)
      console.log('当前用户信息:', authStore.user)
      
      // 确保本地存储已更新
      if (!localStorage.getItem('token') || !localStorage.getItem('user')) {
        console.warn('本地存储中没有找到token或用户信息，正在重新设置...')
        if (authStore.token) {
          localStorage.setItem('token', authStore.token)
        }
        if (authStore.user) {
          localStorage.setItem('user', JSON.stringify(authStore.user))
        }
      }
      
      // 登录成功，跳转到重定向地址或首页
      const redirectPath = route.query.redirect as string || '/'
      console.log('重定向到:', redirectPath)
      
      // 使用replace而不是push，确保不能回退到登录页
      router.replace(redirectPath)
      
      // 设置检查计时器，确保跳转成功
      setTimeout(() => {
        // 如果3秒后仍然在登录页，强制跳转
        if (router.currentRoute.value.path.includes('/auth/login')) {
          console.warn('检测到跳转失败，正在强制跳转...')
          // 尝试重新加载页面
          window.location.href = redirectPath.startsWith('/') 
            ? window.location.origin + redirectPath
            : redirectPath
        }
      }, 3000)
      
      // 显示成功消息
      ElMessage.success('登录成功，欢迎回来！')
    } else {
      console.error('登录函数返回失败')
      ElMessage.error('登录失败，请检查用户名和密码')
    }
  } catch (error) {
    console.error('登录过程中发生错误', error)
    ElMessage.error('登录过程中发生错误')
  } finally {
    isSubmitting.value = false
  }
}

// 前往注册页
const goToRegister = () => {
  router.push({ name: 'Register', query: route.query })
}

// 前往找回密码页
const goToForgotPassword = () => {
  router.push({ name: 'ForgotPassword' })
}
</script>

<template>
  <div class="login-page">
    <div class="login-container">
      <div class="login-form-wrapper">
        <div class="login-header">
          <h1 class="login-title">欢迎回来</h1>
          <p class="login-subtitle">请登录您的账号以继续使用水印去除工具</p>
        </div>
        
        <el-form
          ref="formRef"
          :model="loginForm"
          :rules="rules"
          label-position="top"
          class="login-form"
          @keyup.enter="handleSubmit"
        >
          <el-form-item prop="username">
            <el-input
              v-model="loginForm.username"
              placeholder="请输入用户名"
              size="large"
              :prefix-icon="User"
              class="custom-input"
              clearable
            />
          </el-form-item>
          
          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              size="large"
              :prefix-icon="Lock"
              show-password
              class="custom-input"
              clearable
            />
          </el-form-item>
          
          <div class="flex-between mb-6">
            <el-checkbox v-model="loginForm.remember" label="记住我" />
            <el-button type="text" class="forgot-link" @click="goToForgotPassword">
              忘记密码？
            </el-button>
          </div>
          
          <el-button
            type="primary"
            class="login-btn"
            size="large"
            :loading="isSubmitting"
            @click="handleSubmit"
          >
            登录
          </el-button>
        </el-form>
        
        <div class="login-footer">
          <div class="divider">
            <span>还没有账号？</span>
          </div>
          
          <el-button
            type="default"
            class="register-btn"
            size="large"
            @click="goToRegister"
          >
            注册新账号
          </el-button>
          
          <div class="other-links">
            <span>社交账号登录</span>
            <div class="social-icons">
              <div class="social-icon"><i class="el-icon-s-platform"></i></div>
              <div class="social-icon"><i class="el-icon-s-custom"></i></div>
              <div class="social-icon"><i class="el-icon-s-goods"></i></div>
            </div>
          </div>
        </div>
      </div>
      
      <div class="login-banner">
        <div class="banner-content">
          <h2 class="banner-title">一键去除水印</h2>
          <p class="banner-text">我们的AI技术能够智能识别并去除任何图片上的水印，保持原图清晰度。</p>
          <div class="banner-features">
            <div class="feature-item">
              <div class="feature-icon"><i class="el-icon-picture"></i></div>
              <div class="feature-text">支持各种类型水印</div>
            </div>
            <div class="feature-item">
              <div class="feature-icon"><i class="el-icon-finished"></i></div>
              <div class="feature-text">处理速度快</div>
            </div>
            <div class="feature-item">
              <div class="feature-icon"><i class="el-icon-lock"></i></div>
              <div class="feature-text">隐私安全保障</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.login-page {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f8fafc;
  padding: 1rem;
}

.login-container {
  display: flex;
  width: 100%;
  max-width: 1000px;
  min-height: 600px;
  background-color: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.05);
}

.login-form-wrapper {
  flex: 1;
  padding: 2.5rem;
  display: flex;
  flex-direction: column;
}

.login-header {
  margin-bottom: 2rem;
  text-align: center;
}

.login-title {
  font-size: 2rem;
  font-weight: 600;
  color: #1a202c;
  margin-bottom: 0.5rem;
}

.login-subtitle {
  color: #718096;
  font-size: 0.95rem;
}

.login-form {
  flex: 1;
}

.custom-input :deep(.el-input__wrapper) {
  padding: 0 15px;
  height: 48px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  border: 1px solid #e2e8f0;
}

.custom-input :deep(.el-input__wrapper:hover) {
  border-color: #13c2c2;
}

.custom-input :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 2px rgba(19, 194, 194, 0.2);
  border-color: #13c2c2;
}

.flex-between {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.mb-6 {
  margin-bottom: 1.5rem;
}

.forgot-link {
  color: #13c2c2;
  font-size: 0.9rem;
}

.login-btn {
  width: 100%;
  height: 48px;
  font-weight: 600;
  border-radius: 6px;
  background-color: #13c2c2;
  border-color: #13c2c2;
  transition: all 0.2s;
}

.login-btn:hover {
  background-color: #36cfc9;
  border-color: #36cfc9;
  transform: translateY(-1px);
}

.login-footer {
  margin-top: 2rem;
}

.divider {
  display: flex;
  align-items: center;
  color: #a0aec0;
  margin: 1.5rem 0;
}

.divider::before,
.divider::after {
  content: '';
  flex: 1;
  border-bottom: 1px solid #e2e8f0;
}

.divider::before {
  margin-right: 1rem;
}

.divider::after {
  margin-left: 1rem;
}

.register-btn {
  width: 100%;
  height: 48px;
  font-weight: 600;
  border-radius: 6px;
}

.other-links {
  margin-top: 1.5rem;
  text-align: center;
  color: #718096;
  font-size: 0.9rem;
}

.social-icons {
  display: flex;
  justify-content: center;
  gap: 1rem;
  margin-top: 1rem;
}

.social-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  background-color: #f7fafc;
  border: 1px solid #e2e8f0;
  transition: all 0.2s;
}

.social-icon:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
  border-color: #13c2c2;
  color: #13c2c2;
}

.login-banner {
  flex: 1;
  background: linear-gradient(135deg, #13c2c2 0%, #006064 100%);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  overflow: hidden;
}

.banner-content {
  position: relative;
  z-index: 2;
  padding: 2.5rem;
  text-align: center;
}

.banner-title {
  font-size: 2.5rem;
  font-weight: 700;
  margin-bottom: 1rem;
}

.banner-text {
  font-size: 1.1rem;
  opacity: 0.9;
  margin-bottom: 2.5rem;
  line-height: 1.6;
}

.banner-features {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.feature-item {
  display: flex;
  align-items: center;
  text-align: left;
}

.feature-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.15);
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 1rem;
  font-size: 1.2rem;
}

.feature-text {
  font-weight: 500;
}

/* 响应式调整 */
@media (max-width: 992px) {
  .login-container {
    flex-direction: column-reverse;
    max-width: 500px;
  }
  
  .login-banner {
    display: none;
  }
  
  .login-form-wrapper {
    padding: 2rem;
  }
}

@media (max-width: 576px) {
  .login-form-wrapper {
    padding: 1.5rem;
  }
  
  .login-title {
    font-size: 1.75rem;
  }
}
</style> 